/**
 * @author 03010570
 * @date 2020/06/15
 * describe:    二分查找    https://leetcode-cn.com/problems/binary-search/
 */
public class LeetCode_704 {

    public static void main(String[] args) {
        System.out.println(1/2);
        int[] ints = new int[]{-1, 0, 3, 5, 9, 12};
        int target = 9;
        System.out.println(search(ints, target));
        ints = new int[]{-1, 0, 3, 5, 9, 12};
        target = 2;
        System.out.println(search(ints, target));

    }

    /**
     * 自己的思路：
     * 1、循环 二分查找  middle = left + (right-left)/2
     *
     * @param nums
     * @param target
     * @return
     */
    public static int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (right >= left) {
            int middle = left + (right - left) / 2;
            if (nums[middle] < target) {
                left = middle + 1;
            } else if (nums[middle] > target) {
                right = middle - 1;
            } else {
                return middle;
            }
        }
        return -1;

    }
}
